using B.S.XZYData.Api.Read.Application.Command.WorkReport;
using B.S.XZYData.Domain.ZSH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using B.S.XZYData.Domain.RBAC;

namespace B.S.XZYData.Api.Read.Application.Handler.WorkReport
{
    /// <summary>
    /// 报工查询处理器
    /// </summary>
    public class QueryWorkReportHandler : IRequestHandler<QueryWorkReportCommand, ApiResult<WorkReportPageResult>>
    {
        // 使用全限定名避免与当前命名空间冲突
        private readonly IBaseRepository<B.S.XZYData.Domain.ZSH.WorkReport> _reportRepo;
        private readonly IBaseRepository<WorkReportDefectiveItem> _defectiveItemRepo;
        private readonly IBaseRepository<AccountModel> _accountRepo;
        private readonly ILogger<QueryWorkReportHandler> _logger;

        public QueryWorkReportHandler(
            IBaseRepository<B.S.XZYData.Domain.ZSH.WorkReport> reportRepo,
            IBaseRepository<WorkReportDefectiveItem> defectiveItemRepo,
            IBaseRepository<AccountModel> accountRepo,
            ILogger<QueryWorkReportHandler> logger)
        {
            _reportRepo = reportRepo;
            _defectiveItemRepo = defectiveItemRepo;
            _accountRepo = accountRepo;
            _logger = logger;
        }

        public async Task<ApiResult<WorkReportPageResult>> Handle(QueryWorkReportCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<WorkReportPageResult>();
            try
            {
                var query = _reportRepo.GetAll().Where(x => !x.IsDeleted);

                // 筛选条件
                if (!string.IsNullOrEmpty(request.WorkOrderCode))
                {
                    query = query.Where(x => x.WorkOrderCode.Contains(request.WorkOrderCode));
                }
                if (!string.IsNullOrEmpty(request.ProcessName))
                {
                    query = query.Where(x => x.ProcessName.Contains(request.ProcessName));
                }
                if (!string.IsNullOrEmpty(request.ProductCode))
                {
                    query = query.Where(x => x.ProductCode.Contains(request.ProductCode));
                }
                if (request.CreateTimeStart.HasValue)
                {
                    query = query.Where(x => x.CreateTime >= request.CreateTimeStart.Value);
                }
                if (request.CreateTimeEnd.HasValue)
                {
                    query = query.Where(x => x.CreateTime <= request.CreateTimeEnd.Value);
                }

                if (request.ProcessStatus.HasValue)
                {
                    query = query.Where(x => x.ProcessStatus == request.ProcessStatus.Value);
                }

                // 排序
                query = ApplySorting(query, request.SortField, request.SortDirection);

                var total = await query.CountAsync();

                var reports = await query
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync();

                // 获取报工ID列表，用于查询不良品项
                var reportIds = reports.Select(r => r.Id).ToList();
                
                // 查询不良品项
                var defectiveItems = await _defectiveItemRepo.GetAll()
                    .Where(d => !d.IsDeleted && reportIds.Contains(d.WorkReportId))
                    .ToListAsync();

                // 取创建人、修改人名称 (包括报工表和不良品项表的用户)
                var userIds = reports.SelectMany(r => new List<int?> { r.CreatorId, r.ModifierId })
                    .Concat(defectiveItems.SelectMany(d => new List<int?> { d.CreatorId, d.ModifierId }))
                    .Where(id => id.HasValue)
                    .Select(id => id!.Value)
                    .Distinct()
                    .ToList();
                    
                var users = _accountRepo.GetAll().Where(u => userIds.Contains((int)u.Id)).ToList();

                var data = reports.Select(r => new WorkReportDto
                {
                    Id = r.Id,
                    WorkOrderCode = r.WorkOrderCode,
                    ProcessName = r.ProcessName,
                    ProductCode = r.ProductCode,
                    ProductNo = r.ProductNo,
                    ProductName = r.ProductName,
                    ProductSpec = r.ProductSpec,
                    ProcessStatus = r.ProcessStatus.ToString(),
                    Producer = r.Producer,
                    ReportQty = r.ReportQty,
                    Unit = r.Unit,
                    GoodQty = r.GoodQty,
                    DefectiveQty = r.DefectiveQty,
                    ProcessProgress = r.ProcessProgress,
                    StartTime = r.StartTime,
                    EndTime = r.EndTime,
                    ReportHours = r.ReportHours,
                    ReportMinutes = r.ReportMinutes,
                    StandardEfficiency = r.StandardEfficiency,
                    ActualEfficiency = r.ActualEfficiency,
                    ComplianceRate = r.ComplianceRate,
                    PricingMethod = r.PricingMethod.ToString(),
                    WageUnitPrice = r.WageUnitPrice,
                    EstimatedWage = r.EstimatedWage,
                    // ApprovalStatus  Approver 可从流程表获取，这里先留空
                    ApprovalStatus = null,
                    Approver = null,
                    CreateTime = r.CreateTime,
                    CreatorName = users.FirstOrDefault(u => u.Id == r.CreatorId)?.RealName,
                    ModifyTime = r.ModifyTime,
                    ModifierName = users.FirstOrDefault(u => u.Id == r.ModifierId)?.RealName,
                    // 填充不良品项列表
                    DefectiveItems = defectiveItems
                        .Where(d => d.WorkReportId == r.Id)
                        .Select(d => new WorkReportDefectiveItemDto
                        {
                            Id = d.Id,
                            WorkReportId = d.WorkReportId,
                            DefectiveCode = d.DefectiveCode,
                            DefectiveQty = d.DefectiveQty,
                            CreateTime = d.CreateTime,
                            CreatorName = users.FirstOrDefault(u => u.Id == d.CreatorId)?.RealName,
                            ModifyTime = d.ModifyTime,
                            ModifierName = users.FirstOrDefault(u => u.Id == d.ModifierId)?.RealName
                        })
                        .OrderBy(d => d.Id)
                        .ToList()
                }).ToList();

                var pageResult = new WorkReportPageResult
                {
                    Data = data,
                    Total = total,
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize
                };

                res.Code = ApiEnum.Success;
                res.Msg = "查询成功";
                res.Data = pageResult;
                return res;
            }
            catch (Exception ex)
            {
                _logger.LogError($"查询报工信息异常：{ex.Message}");
                res.Code = ApiEnum.Error;
                res.Msg = "查询报工信息失败：" + ex.Message;
                return res;
            }
        }

        private ISugarQueryable<B.S.XZYData.Domain.ZSH.WorkReport> ApplySorting(ISugarQueryable<B.S.XZYData.Domain.ZSH.WorkReport> query, string field, string direction)
        {
            switch (field.ToLower())
            {
                case "createtime":
                    return direction.ToLower() == "asc" ? query.OrderBy(r => r.CreateTime) : query.OrderByDescending(r => r.CreateTime);
                case "workordercode":
                    return direction.ToLower() == "asc" ? query.OrderBy(r => r.WorkOrderCode) : query.OrderByDescending(r => r.WorkOrderCode);
                default:
                    return query.OrderByDescending(r => r.Id);
            }
        }
    }
} 